package com.reggie.controller;

import com.reggie.common.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String filePath = "D://Java//img//" + originalFilename;
        File saveFile = new File(filePath);
        file.transferTo(saveFile);
        return R.success(originalFilename);
    }

    @GetMapping("/download")
    public R<String> download(String name, HttpServletResponse response) throws IOException {
        String filePath = "D://Java//img//" + name;
        FileInputStream fileInputStream = new FileInputStream(filePath);

        ServletOutputStream outputStream =  response.getOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while( (len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        return R.success("下载成功");
    }
}
